import React, {useEffect} from 'react';
import {Divider, List, Popover} from 'antd';
import {connect} from 'umi';
import styles from './index.less';

const Step1 = ({dispatch, bookInfo: {list = [],}, loading}) => {

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'bookInfo/fetchCategory',
      });
    }
  }, []);

  const finishCategory = (termTypeId, termName) => {
    if (dispatch) {
      dispatch({
        type: 'bookInfo/saveStepFormData',
        payload: {termTypeIds: [{label: termName, value: termTypeId}]},
      });
      dispatch({
        type: 'bookInfo/saveCurrentStep',
        payload: 'info',
      });
    }
  };

  const rendItem = (item) => {
    if (!item.children)
      return "";
    let len = item.children.length;
    let mLen = len;
    len = len >= 4 ? 4 : len;
    mLen = mLen >= 3 ? 3 : mLen;

  return item.children && <List
    className={styles.itemList}
    dataSource={item.children || []}
    grid={{ gutter: 16, xs: mLen, sm: mLen, md: len, lg: len, xl: len, xxl: len, }}
    renderItem={(it) => (
      <List.Item>
        <a onClick={async () => finishCategory(it.key, it.title)}>
          {it.title}
        </a>
      </List.Item>
    )}
  />;
  };

  const cardList = list && (<List
    rowKey="id"
    loading={loading}
    grid={{gutter: 5,xs: 3,sm: 3,md: 4,lg: 4,xl: 4,xxl: 4,}}
    dataSource={list}
    renderItem={(item) => (
      <List.Item>
        <Popover placement="right" title={item.title} content={rendItem(item)} trigger="hover">
          {item.title}
        </Popover>
      </List.Item>
    )}
  />);

  return (
    <div className={styles.categoryList}>
      { cardList }
      <Divider
        style={{
          margin: '40px 0 24px',
        }}
      />
      <div className={styles.desc}>
        <h3>说明</h3>
        <h4>选择分类</h4>
        <p>
          PC端鼠标移动到分类上，弹出小类选择框，点击选定的小类打开信息编辑页；移动端需要点击分类弹出小类选择框。
        </p>
        <h4>填写信息</h4>
        <p>
          填写信息需要上传封面图和主图，如果不上传，会展示默认封面，默认封面不具备显著特征不易被识别，主图至少上传一张。
        </p>
      </div>
    </div>
  );
};

export default connect(({bookInfo, loading}) => ({
  bookInfo,
  loading: loading.models.category,
}))(Step1);
